package com.room.controller.verify;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/check")
public class CheckCodeController {

    @RequestMapping(value = "/checkcode",method = RequestMethod.GET)
    public Object getCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int charNum = 4;
        int width = 20 * 4;
        int height = 28;
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);
        graphics.drawRect(0, 0, width - 1, height - 1);
        graphics.setFont(new Font("宋体", Font.BOLD, 22));
        String s = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        Random random = new Random();
        String msg = "";
        int x = 5;
        for (int i = 0; i < charNum; i++) {
            int index = random.nextInt(32);
            String content = String.valueOf(s.charAt(index));
            msg += content;
            graphics.setColor(new Color(random.nextInt(128),
                    random.nextInt(128), random.nextInt(128)));
            graphics.drawString(content, x, 22);
            x += 20;
        }
        request.getSession().setAttribute("checkcode", msg);
        graphics.setColor(new Color(random.nextInt(128),
                random.nextInt(128), random.nextInt(128)));
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }
        graphics.dispose();
//        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        String base64String = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "PNG", bos);

        byte[] bytes = bos.toByteArray();
        Base64.Encoder encoder = Base64.getEncoder();
        base64String = encoder.encodeToString(bytes);
        Map<String,Object> result = new HashMap<>();
        result.put("url", "data:image/png;base64," + base64String);
        return result;
    }
}
